package com.zdkj.subway.check.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.entity.SwAuTvmMoneyAssist;
import com.zdkj.subway.check.entity.SwParamLine;
import com.zdkj.subway.check.entity.SwParamStation;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuTvmMoneyAssistMapper;
import com.zdkj.subway.check.mapper.SwParamLineMapper;
import com.zdkj.subway.check.mapper.SwParamStationMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.LocalDateConverter;
import com.zdkj.subway.check.util.LocalDateTimeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
/**
 * 数据协查管理-TVM票款差异协查-TVM票款差异协查
 * 数据协查管理-TVM票款差异协查-TVM系统差异-TVM系统数据差异
 * TVM票款差异协查-票款差异明细表 SW_AU_TVM_MONEY_ASSIST 根据不同权限修改
 */
@Service
@Slf4j
public class SwAuTvmMoneyAssistService {

    @Resource
    private SwAuTvmMoneyAssistMapper swAuTvmMoneyAssistMapper;
    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    /**
     * 导出
     * @param
     * @return
     */
    public void export(String ids, String tag, SwAuTvmMoneyAssist params, HttpServletResponse response) throws ParseException {
        //线路、站点、支付方式中文名 根据未回馈的查询 差异类型 compare_type = 4 and assist_status =2
        List<SwAuTvmMoneyAssist> records = new ArrayList<>();
        if(ids == null || ids.isEmpty()) {
            Map<String,String> param = new HashMap<>();
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getLineCode())){
                param.put("lineCode",params.getLineCode());
            }else {
                if(StringUtils.isEmpty(params.getLineCode())) {
                    List<String> lineCodeList = new ArrayList<>();
                    PigxUser user = SecurityUtils.getUser();
                    Map<String, Object> p1 = new HashMap<>();
                    p1.put("user_code", user.getUserCode());
                    List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
                    SysUser sysUser = sysUsers.get(0);
                    String managementLineStation = sysUser.getManagementLineStation();
                    if (!StringUtils.isEmpty(managementLineStation)) {
                        JSONArray managementLineStations = JSONArray.parseArray(managementLineStation);
                        for (int i = 0; i < managementLineStations.size(); i++) {
                            JSONObject jsonObject1 = managementLineStations.getJSONObject(i);
                            //存在多条线路
                            lineCodeList.add(jsonObject1.getString("line"));
                        }
                        param.put("lineCode", org.apache.commons.lang3.StringUtils.join(lineCodeList,","));
                    }else {
                        //不管辖线路
                        param.put("lineCode", sysUser.getLineCode());
                    }
                }

            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getStationCode())){
                param.put("stationCode",params.getStationCode());
            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getTvmOrder())){
                param.put("tvmOrder",params.getTvmOrder());
            }
            if(params.getSettleTime()!=null){
                param.put("settleTime", params.getSettleTime());
            }
            param.put("assistInvestStatus", params.getAssistInvestStatus());
            param.put("kyAssistInvestStatus", params.getKyAssistInvestStatus());
            List<Map<String, Object>> swAuTvmMoneyAssistList = swAuTvmMoneyAssistMapper.getTvmMoneyAssistLists(param);
            records = getMapList(swAuTvmMoneyAssistList);
        }else {
            Map<String,String> param = new HashMap<>();
            param.put("ids",ids);
            List<Map<String, Object>> swAuTvmMoneyAssistList = swAuTvmMoneyAssistMapper.getTvmMoneyAssistLists(param);
            records = getMapList(swAuTvmMoneyAssistList);
        }
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = null;
            WriteSheet writeSheet = null;
            if("keyun".equals(tag)){
                fileName = URLEncoder.encode("TVM分钱箱票款差异客运协查", "UTF-8");
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuKeYunTvmMoneyAssistExcelTemplate.xlsx");
                writeSheet = EasyExcel.writerSheet("TVM分钱箱票款差异客运协查").build();
            }else {
                fileName = URLEncoder.encode("TVM分钱箱票款差异机电协查", "UTF-8");
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuTvmMoneyAssistExcelTemplate.xlsx");
                writeSheet = EasyExcel.writerSheet("TVM分钱箱票款差异机电协查").build();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter())
                    .withTemplate(excelTemplateIs).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            //直接写入Excel数据(list是我查询并需导出的数据，并且里面的字段和excel需要导出的字段对应)
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TVM分钱箱票款协查导出失败!");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    /**
     * 组织数据
     * @param res
     * @return
     */
    private List<SwAuTvmMoneyAssist> getMapList(List<Map<String, Object>> res) {
        List<SwAuTvmMoneyAssist> records = new ArrayList<>();
        for (int i = 0; i < res.size(); i++) {
            Map<String, Object> map = res.get(i);
            SwAuTvmMoneyAssist swAuTvmMoneyAssist = new SwAuTvmMoneyAssist();
            swAuTvmMoneyAssist.setId((Integer) map.get("id"));
            SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, map.get("lineCode")));
            SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                    .eq(SwParamStation::getLineCode,map.get("lineCode")).eq(SwParamStation::getCode, map.get("stationCode")));
            swAuTvmMoneyAssist.setLineCode(swParamLine.getName());
            swAuTvmMoneyAssist.setStationCode(swParamStation.getName());
            swAuTvmMoneyAssist.setTvmOrder((String) map.get("tvmOrder"));
            swAuTvmMoneyAssist.setSettleDate(DateFormat.StringTurnLocalDate(map.get("settleTime").toString()));
            swAuTvmMoneyAssist.setSystemMoney(getFixed(map.get("systemMoney")));
            swAuTvmMoneyAssist.setDiffMoney(getFixed(map.get("diffMoney")));
            swAuTvmMoneyAssist.setTvmUnloadMoney(getFixed(map.get("tvmUnloadMoney")));
            swAuTvmMoneyAssist.setReplyDsiplayMoney(getFixed(map.get("replyDsiplayMoney")));
            swAuTvmMoneyAssist.setActualMoney(getFixed(map.get("actualMoney")));
            swAuTvmMoneyAssist.setReplyActualMoney(getFixed(map.get("replyActualMoney")));
            swAuTvmMoneyAssist.setLoadUnloadMoney(getFixed(map.get("loadUnloadMoney")));
            swAuTvmMoneyAssist.setReplyLoadUnloadMoney(getFixed(map.get("replyLoadUnloadMoney")));
            swAuTvmMoneyAssist.setSupplementMoney(getFixed(map.get("supplementMoney")));
            swAuTvmMoneyAssist.setReplySupplementMoney(getFixed(map.get("replySupplementMoney")));
            swAuTvmMoneyAssist.setHandOutMoney(getFixed(map.get("handOutMoney")));
            swAuTvmMoneyAssist.setReplyHandOutMoney(getFixed(map.get("replyHandOutMoney")));
            swAuTvmMoneyAssist.setReplyContent((String) map.get("replyContent"));
            swAuTvmMoneyAssist.setKyReplayConent((String) map.get("kyReplayConent"));
            swAuTvmMoneyAssist.setOperatorId((Integer) map.get("operatorId"));
            swAuTvmMoneyAssist.setOperatorCode((String) map.get("operatorCode"));
            swAuTvmMoneyAssist.setOperatorCode((String) map.get("operatorCode"));//机电回馈人工号
            swAuTvmMoneyAssist.setOperatorName((String) map.get("operatorName"));//机电回馈人
            swAuTvmMoneyAssist.setKyOperatorCode((String) map.get("kyOperatorCode"));//客运回馈人工号
            swAuTvmMoneyAssist.setKyOperatorName((String) map.get("kyOperatorName"));//客运回馈人
            swAuTvmMoneyAssist.setBoxCashName((String) map.get("boxCashName"));//钱箱类型
            swAuTvmMoneyAssist.setJdReplyStatus(StringUtils.isEmpty(String.valueOf(map.get("jdReplyStatus"))) ? "未回馈" : ("0".equals(String.valueOf(map.get("jdReplyStatus"))) ? "未回馈" : "已回馈"));
            swAuTvmMoneyAssist.setReplyReason(map.get("replyReason") ==null ? " " : (map.get("replyReason").equals("1") ? "系统原因" : "非系统原因"));
            swAuTvmMoneyAssist.setKyReplyStatus(StringUtils.isEmpty(String.valueOf(map.get("kyReplyStatus"))) ? "未回馈" : ("0".equals(String.valueOf(map.get("kyReplyStatus"))) ? "未回馈" : "已回馈"));
            swAuTvmMoneyAssist.setKyReplyReason(map.get("kyReplyReason") ==null ? " " : (map.get("kyReplyReason").equals("1") ? "系统原因" : "非系统原因"));
            if(map.get("replyDateTime")!=null){
                swAuTvmMoneyAssist.setJdReplyDateTime(DateFormat.StringTurnLocalDateTime(map.get("replyDateTime").toString()));
            }
            if(map.get("sendDateTime")!=null){
                swAuTvmMoneyAssist.setSendDateTime(DateFormat.StringTurnLocalDateTime(map.get("sendDateTime").toString()));
            }
            records.add(swAuTvmMoneyAssist);
        }
        return records;
    }

    /**
     * 金额转换
     * @param money
     * @return
     */
    private BigDecimal getFixed(Object money){
        try {
            BigDecimal num = new BigDecimal("100");
            BigDecimal moneyDecimal = new BigDecimal(String.valueOf(money));
            BigDecimal itemMoney = moneyDecimal.divide(num);
            return itemMoney;

        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
    public Result getSwAuTvmMoneyAssistList(JSONObject jsonObject) {

        //分页
        Integer startPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");

        //线路名称
        String lineCode = jsonObject.getString("lineCode");
        //tvm编号
        String tvmOrder = jsonObject.getString("tvmOrder");
        //站点名称
        String stationCode = jsonObject.getString("stationCode");
        //回馈状态
        String replyStatus = jsonObject.getString("replyStatus");
        String jdReplyStatus = jsonObject.getString("jdReplyStatus");
        String kyReplyStatus = jsonObject.getString("kyReplyStatus");

        //收入时间
        Date settleTime = jsonObject.getDate("settleTime");
        Date startTime = jsonObject.getDate("startTime");
        Date endTime = jsonObject.getDate("endTime");

        Example example = new Example(SwAuTvmMoneyAssist.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(lineCode)) {
            criteria.andEqualTo("lineCode", lineCode);
        }
        if (!StringUtils.isEmpty(lineCode)) {
            criteria.andEqualTo("stationCode", stationCode);
        }
        if (!StringUtils.isEmpty(tvmOrder)) {
            criteria.andEqualTo("tvmOrder", tvmOrder);
        }
        if (!StringUtils.isEmpty(replyStatus)) {
            criteria.andEqualTo("replyStatus", replyStatus);
        }
        if (!StringUtils.isEmpty(jdReplyStatus)) {
            criteria.andEqualTo("jdReplyStatus", jdReplyStatus);
        }
        if (!StringUtils.isEmpty(kyReplyStatus)) {
            criteria.andEqualTo("kyReplyStatus", kyReplyStatus);
        }
        if(null != settleTime){
            criteria.andEqualTo("settleTime", settleTime);
        }
        if (startTime != null && endTime != null) {
            criteria.andBetween("settleTime", startTime, endTime);
        }

        PageHelper.startPage(startPage,pageSize);
        List<SwAuTvmMoneyAssist> swAuTvmMoneyAssists = swAuTvmMoneyAssistMapper.selectByExample(example);
        PageInfo<SwAuTvmMoneyAssist> swAuTvmMoneyAssistPageInfo = new PageInfo<>(swAuTvmMoneyAssists);

        JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmMoneyAssists);
        resultJson.put("pageInfo", swAuTvmMoneyAssistPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);
    }

    /**
     * TVM票款差异协查-票款差异明细表 单独查询
     * @param jsonObject
     * @return
     */
    public Result getSwAuTvmMoneyAssist(JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        SwAuTvmMoneyAssist swAuTvmMoneyAssist = swAuTvmMoneyAssistMapper.selectByPrimaryKey(id);
        JSONObject resultJson = new JSONObject();
        resultJson.put("obj",swAuTvmMoneyAssist);
        return new Result(ResultDetailMsg.OK,resultJson);
    }

    public Result updateSwAuTvmMoneyAssist(JSONObject jsonObject) {
        SwAuTvmMoneyAssist swAuTvmMoneyAssist =
                JSONObject.parseObject(jsonObject.toJSONString(), SwAuTvmMoneyAssist.class);
        int i = swAuTvmMoneyAssistMapper.updateByPrimaryKeySelective(swAuTvmMoneyAssist);
        return new Result(ResultDetailMsg.OK);
    }
}
